<template>
  <vxe-grid ref="logisticsXGrid" v-bind="gridOptions" :edit-rules="validRules">
    <template #operate="{ row }">
      <a-tooltip placement="top" title="移除货物" v-if="!$props.isDetail">
      <vxe-button
status="danger" icon="vxe-icon-close" size="medium" round
        @click="removeRow(row)"
        style="font-size: 11px;height: 1.4rem;"/>
      </a-tooltip>
    </template>

    <template #name_edit="{ row }">
        <a-select
          v-model:value="row.cid"
          show-search
          style="width: 100%"
          :allow-clear="false"
          size="large"
          :options="carrierList"
          :field-names="{
            value: 'ID',
            label: 'name',
          }"
          placeholder="请选择"
          @select="(_, options) => row.name = options.name"
        />
    </template>

    <template #sendAt_edit="{ row }">
      <vxe-input v-model="row.sendAt" placeholder="请选择" type="datetime" transfer />
    </template>
    <template #waybill_edit="{ row }">
      <vxe-textarea
v-model="row.waybill" placeholder="快递单号" resize="vertical" 
      clearable maxlength="60" showWordCount />
    </template>
    <template #memo_edit="{ row }">
      <vxe-textarea v-model="row.memo" resize="vertical" maxlength="100" showWordCount/>
    </template>
  </vxe-grid>
</template>
<script lang="tsx" name="LogisticsOfEditList" setup>
// import { ShowSearchType } from "and-design-vue";
import __ from 'lodash-es';
import { reactive, ref, toRaw, watch, } from 'vue';
import { VxeGridProps, VxeTablePropTypes, } from 'vxe-table';
import { logisticsListColumns } from './data';
import { CarrierItem, getListData as getCarrierListData } from "/@/api/wms/carrier";

const props = defineProps({
  show: Boolean,
  isDetail: Boolean,
  dataList: {type: [Array<any>, null] as PropType<Array<any> | null>, default: new Array(5),},
})

watch(() => props.dataList, (v1, _) => {
  if (v1 && v1.length > 0) {
    let list = v1.map((e:any) => {
      return {
        ID: e.ID, billId: e.billId, cid: e.cid, name: e?.carrier?.name,
        sendAt: e.sendAt, waybill: e.waybill,
        memo: e.memo,
      }
    })
    pushTableData(list)
  }
})
const enabled = ref(true)
const buttons = ref([
    { code: 'insert_actived', name: '添加运送信息', icon: 'vxe-icon-add', },
    ])
watch(()=>props.isDetail, (v1, _) => {
  if (v1) {
    enabled.value = false
    buttons.value = []
  }
},{immediate: true})

const validRules = ref({
  // blur,change,manual
  wid: [
    { required: true, validator: ({ cellValue, }) => {
      if (!cellValue || cellValue <= 0) {
        return new Error('请选择仓库')
      }
    }},
  ],
  qty: [
    { required: true, validator: ({ cellValue, }) => {
      if (cellValue <= 0) {
        return new Error('数量必须大于0')
      }
    },},
  ],
} as VxeTablePropTypes.EditRules)

const logisticsXGrid = ref()
const gridOptions = reactive<VxeGridProps>({
  id: 'goodsListOfOutbound',
  border: false,
  stripe: true,
  // size: 'medium',
  // maxHeight: window.innerHeight - 320,
  keepSource: true,
  loading: false,
  resizable: true,
  showFooter: false,
  showOverflow: false,
  highlightCurrentRow: false,
  highlightHoverRow: true,
  highlightCurrentColumn: true,
  highlightHoverColumn: true,
  // emptyRender: {name: 'NotDataOfSelectGoods', events: {click: ()=> modalOfGoods.data.show = true},},
  rowConfig: {
    useKey: true,
    isCurrent: false,
    isHover: true,
    keyField: 'goodsId',
  },
  columnConfig: {
    useKey: true,
    isCurrent: false,
    isHover: true,
  },
  customConfig: {
    storage: true,
  },
  sortConfig: {
    trigger: 'default',
    remote: false
  },
  filterConfig: {
    remote: false
  },
  mouseConfig: {selected: true},
  keyboardConfig: {
    isArrow: true,
    isEnter: false,
    isDel: false, 
    isTab: true,
    enterToTab: false,
    isEdit: true, 
    isChecked: true,
  },
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    enabled: enabled.value,
    showStatus: false,
    showAsterisk: true,
    autoClear: true,
    beforeEditMethod: ({ row, column, }) => {
      if (row.isGift !== 2 && column.field === 'price') {
        return false
      }
      return true
    }
  },
  toolbarConfig: {
    zoom: false,
    custom: false,
    buttons: buttons.value,
    // slots: {
    //   buttons: 'toolbar_buttons',
    //   // tools: 'toolbar_right',
    // }
  },
  columns: [
  { title: '操作', sortable: false, visible: true, width: 60, align: 'center', fixed: 'left', 
    slots: {default: 'operate', header: ({}) => {
      return (
        // <Popconfirm title="您要移除『全部商品』吗?" ok-text="全部移除"
        // onConfirm={() => removeGoodsRow()}>
        //   <vxe-button status="danger" icon="vxe-icon-close" size="mini" round 
        //   disabled={props.dataList && props.dataList.length <= 1}
        //   title="移除全部商品"
        //   style="font-size: 1px;height: 16px;"/>
        // </Popconfirm>
        <span></span>
      )
    },}
  },
  ...logisticsListColumns,
  ],
  data: [] as any[],
})

const carrierList = ref<CarrierItem[]>()
  getCarrierListData().then(dd => {
    carrierList.value = dd.map(e => {
      return { ...e, disabled: e.enable == 2}
    })
})

const removeRow = (row?:any) => {
  logisticsXGrid.value.remove(row)
}

function pushTableData(list:any[]) {
  if (!(list && list.length > 0)) return
  let one:any = null
  if (list.length > 0) {
    one = list[0]
  }
  let {fullData} = logisticsXGrid.value.getTableData()
  fullData.forEach((e1:any) => {
    list.forEach((e2:any) => {
      if (e1.goodsId === e2.goodsId && e1.wid === e2.wid) {
        e1.qty++
        e1.amount = e1.qty * e1.price
        __.remove(list, (e3:any) => e1.goodsId === e3.goodsId)
      }
    })
  })
  logisticsXGrid.value.loadData(__.concat(fullData, list))

  let axtRow = list[0] ?? fullData[0]
  if (one) axtRow = fullData.find((e:any) => e.goodsId === one.goodsId && e.wid === one.wid) || one
  logisticsXGrid.value.setEditCell(axtRow, 'qty')
}

defineExpose({
  getList: async () => {
    let result = await logisticsXGrid.value.fullValidate(true).then(info => {
      if (info) {
        return null
      } else {
        let {fullData} = logisticsXGrid.value.getTableData()
        return toRaw(fullData);
      }
    })
    return result
  },
  getTable: () => {
    return logisticsXGrid.value
  },
});
</script>

<style scoped>
:deep().vxe-input--prefix-icon{
  display: flex;
  margin: 0 20px;
}
:deep().selectBtn{
  font-size:.8rem;
  /* margin: 0px -9px; */
  margin-right: -9px;
  padding: 0px 12px;
}
:deep().selectBtn:hover{
  background: rgba(220,220,220,.5);
}
:deep().search-goods-input input{
  color:black;
  opacity: .8;
  font-size: .9rem;
  font-weight: bold;
  margin-left: 10px;
}

:deep().vxe-footer--row{
  background: rgba(250,250,250,.6);
  font-weight: bold;
}
</style>
